package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.BaseUserDao;
import com.hhs.storage.dao.ProjectPlanDao;
import com.hhs.storage.dao.ProjectWorkFlowDao;
import com.hhs.storage.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.StringUtil;
import com.hhs.storage.util.SysUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-01-13
 */
@Service
@Transactional
public class ProjectPlanServiceImpl extends ServiceImpl<ProjectPlanDao, ProjectPlan> implements ProjectPlanService {
    @Resource
    private HttpServletRequest request;
    @Resource
    private ProjectMemberService projectMemberService;
    @Resource
    private BaseUserService userService;
    @Resource
    private PersonalPlanService personalPlanService;
    @Resource
    private BaseRoleService roleService;
    @Resource
    private ProjectWorkFlowService workFlowService;
    @Resource
    private BaseDepartmentService departmentService;
    @Resource
    private TopicMessageService topicMessageService;
    @Resource
    private AttachmentListService attachmentListService;
    @Resource
    private BaseUserDao userDao;
    @Resource
    private TopicUserRefuseCountService topicUserRefuseCountService;

    @Override
    public Map<String, Object> getDetailById(String id) {
        ProjectPlan projectPlan = this.getById(id);
        if (projectPlan == null) {
            return ResponseInfo.error("错误的参数");
        }
        //查询成员
        QueryWrapper<ProjectMember> qw = new QueryWrapper<>();
        qw.eq("project_id", id);
        qw.orderByAsc("identity_type");
        List<ProjectMember> projectMemberList = projectMemberService.list(qw);
        for (int i = 0; i < projectMemberList.size(); i++) {
            ProjectMember member = projectMemberList.get(i);
            BaseUser user = userService.getById(member.getUserId());
            member.setName(user.getName());
            member.setUser(user);
            //设置工序

        }
        //按创建时间排序
        projectMemberList.sort(new Comparator<ProjectMember>() {
            @Override
            public int compare(ProjectMember o1, ProjectMember o2) {
                return o1.getUser().getOrderNum().compareTo(o2.getUser().getOrderNum());
            }
        });
        projectPlan.setProjectMemberList(projectMemberList);
        //查询工序
        QueryWrapper qw2 = new QueryWrapper<ProjectWorkFlow>();
        qw2.eq("project_plan_id", id);
        qw2.orderByAsc("step");
        List<ProjectWorkFlow> projectWorkFlowList = workFlowService.list(qw2);
        projectPlan.setProjectWorkFlowList(projectWorkFlowList);
        //查询项目创建者
        BaseUser user=userService.getById(projectPlan.getUserId());
        projectPlan.setUser(user);
        //查询项目所属部门
        if(StringUtils.isNotEmpty(projectPlan.getDepartId())){
            BaseDepartment department = departmentService.getById(projectPlan.getDepartId());
            projectPlan.setDepartName(department.getName());
        }
        //查询留言总数
        QueryWrapper<TopicMessage> qwtm=new QueryWrapper<>();
        qwtm.eq("bak_topic_id",projectPlan.getId()+"-type-3");
        String loginUserId = SysUtil.getLoginUserId(request);
        if(!"2".equals(loginUserId)&&!"21".equals(loginUserId)&&!isProjectHeader(projectPlan.getId())){
            qwtm.and(wrapper -> wrapper.eq("user_id",loginUserId).or().eq("reply_user_id",loginUserId));
        }
        int count = topicMessageService.count(qwtm);
        projectPlan.setLeaveWordC(count);
        return ResponseInfo.success(projectPlan);
    }

    @Override
    public Map<String, Object> getProjectPlansByUserId(String userId, LocalDate workDate) {
        QueryWrapper<ProjectPlan> qw = new QueryWrapper<>();

        if (StringUtils.isEmpty(userId)) {//如果用户id等于空，那就使用当前登录用户
            userId = SysUtil.getLoginUserId(request);
        } else {
//            String loginUserId=SysUtil.getLoginUserId(request);
//            if (!userId.equals(loginUserId)){//是当前用户帮其他用户查询相关项目信息
//                //帮忙查询的人必须是项目负责人
//                qw.inSql("id","select project_id from project_member where identity_type=0 and user_id='"+loginUserId+"'");
//            }
        }
        qw.inSql("id", "select project_id from project_member where user_id='" + userId + "'");
        if (workDate != null) {
            qw.le("start_time", workDate);
            qw.ge("end_time", workDate);
        }
        List<ProjectPlan> list = this.list(qw);
        return ResponseInfo.success(list);
    }

    /**
     * 查询计划信息
     *
     * @param projectPlan dataType 根据类型查询项目 ：all=全部项目  my=个人项目
     * @param projectPlan name 根据项目名查询
     * @param projectPlan state 根据项目名状态
     * @param projectPlan memberId 根据项目成员查询
     * @param inputParam  page,size 分页参数
     * @param inputParam  completeTimeStartDate completeTimeEndDate 根据项目完成时间的开始日期，结束日期查询
     * @return
     */
    @Override
    public Map<String, Object> getAll(ProjectPlan projectPlan, InputParam inputParam) {
        QueryWrapper<ProjectPlan> ew = new QueryWrapper();
        if (!StringUtils.isEmpty(projectPlan.getName())) {//名称查询
            ew.like("name", projectPlan.getName());
        }
        if (projectPlan.getState() != null) {//状态查询
            ew.eq("state", projectPlan.getState());
        }
        //查询个人相关的项目数据
        String loginUserId = SysUtil.getLoginUserId(request);
        if (StringUtils.isNotEmpty(inputParam.getDataType()) && "my".equals(inputParam.getDataType())) {
            ew.inSql("id", "SELECT project_id FROM project_member WHERE user_id='" + loginUserId + "'");
        }else{
            if(!"xmjhck".equals(inputParam.getPermission())){
                ew.inSql("id", "SELECT project_id FROM project_member WHERE user_id='" + loginUserId + "'");
            }
        }
        //根据项目成员查询,查询与成员相关的数据
        if (StringUtils.isNotEmpty(projectPlan.getMemberId())) {
            ew.inSql("id", "SELECT project_id FROM project_member WHERE user_id='" + projectPlan.getMemberId() + "'");
        }

        //根据项目所属公司部门查询
        if (StringUtils.isNotEmpty(projectPlan.getDepartId())) {
            String tempSql="select id from base_department a where FIND_IN_SET('"
                    +projectPlan.getDepartId()+"',ancestor) or id='"
                    +projectPlan.getDepartId()+"'";
            ew.inSql("depart_id",tempSql);
            if(SysUtil.TOP_DEPART_ID.equals(projectPlan.getDepartId())){
                ew.or().isNull("depart_id");
            }
        }
        //根据项目完成时间的开始日期，结束日期查询
        if (inputParam.getCompleteTimeStartDate() != null && inputParam.getCompleteTimeEndDate() != null) {
            ew.between("complete_time", inputParam.getCompleteTimeStartDate().atStartOfDay(),
                    inputParam.getCompleteTimeEndDate().atTime(LocalTime.MAX));
        }
        ew.orderByDesc("create_time");
        Page<ProjectPlan> result = this.page(new Page<ProjectPlan>(
                inputParam.getPage(),
                inputParam.getSize()), ew);
        Map<String, Object> map = new HashMap<String, Object>();
        List<ProjectPlan> list = result.getRecords();

        for (int i = 0; i < list.size(); i++) {
            int countCC=0;
            //获取创建人名称
            ProjectPlan temp = list.get(i);
            BaseUser user = userService.getById(temp.getUserId());
            temp.setUser(user);
            //获取成员列表
            QueryWrapper<ProjectMember> qw = new QueryWrapper<>();
            qw.eq("project_id", temp.getId());
            List<ProjectMember> projectMemberList = projectMemberService.list(qw);
            temp.setProjectMemberList(projectMemberList);
            for (int j = 0; j < projectMemberList.size(); j++) {
                ProjectMember member = projectMemberList.get(j);
                if (member.getIdentityType() == ProjectMember.IDENTITY_IDENTITY_TYPE_HEADER) {
                    BaseUser header = userService.getById(member.getUserId());
                    temp.setHeader(header);
                }
                //得到每个人的工序
                QueryWrapper<ProjectWorkFlow> qws=new QueryWrapper<>();
                qws.eq("project_plan_id",member.getUserId()+"-"+temp.getId());
                qws.eq("type",5);
                List<ProjectWorkFlow> list11 = workFlowService.list(qws);
                for (ProjectWorkFlow pwf:list11){
                    QueryWrapper<AttachmentList> qwa=new QueryWrapper<>();
                    qwa.eq("target_id",pwf.getId());
                    int count = attachmentListService.count(qwa);
                    countCC+=count;
                }
                member.setSubWk(list11);
                //如果根据项目成员查询,添加项目的个人进度
                if (StringUtils.isNotEmpty(projectPlan.getMemberId()) && member.getUserId().equals(projectPlan.getMemberId())) {
                    temp.setMemberProgress(member.getProgress());
                }
            }
            //评价的数据
            //工序
            QueryWrapper<ProjectWorkFlow> qww=new QueryWrapper<>();
            qww.eq("project_plan_id",list.get(i).getId());
            qww.isNull("type");
            List<ProjectWorkFlow> list1 = workFlowService.list(qww);
            //加入
            for (ProjectWorkFlow pwf:list1){
                QueryWrapper<AttachmentList> qwa=new QueryWrapper<>();
                qwa.eq("target_id",pwf.getId());
                int count = attachmentListService.count(qwa);
                countCC+=count;
            }
            list.get(i).setAttC(countCC);
            list.get(i).setProjectWorkFlowList(list1);
        }

        map.put("rows", list);
        map.put("total", result.getTotal());
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> addOrUpdate(ProjectPlan projectPlan, List<ProjectMember> projectMembers, List<ProjectWorkFlow> projectWorkFlows) {
        //只有经理，总经理，老板有权限新增编辑删除
//        String[] roles=new String[]{SysUtil.ROLE_FLAG_JL,SysUtil.ROLE_FLAG_ZJL,SysUtil.ROLE_FLAG_BOSS};
//        boolean flag=roleService.hasRoles(roles,SysUtil.getLoginUserId(request));
//        if (flag==false){
//            return ResponseInfo.error("当前账号无权限，必须是【经理，总经理，老板】角色账户");
//        }
        if (StringUtils.isEmpty(projectPlan.getName()) //项目名
//        ||StringUtils.isEmpty(projectPlan.getContent()) //内容
                || projectPlan.getStartTime() == null //开始时间
                || projectPlan.getEndTime() == null) { //结束时间
            return ResponseInfo.error("项目基本信息不完全");
        }
        if (projectPlan.getStartTime().isAfter(projectPlan.getEndTime())) {
            return ResponseInfo.error("项目开始时间必须小于项目结束时间");
        }
        if (projectPlan.getType()==null) {
            return ResponseInfo.error("项目更新类型没有");
        }
        if (projectPlan.getType()==0) {
            //type 为0，新增
            return add(projectPlan, projectMembers, projectWorkFlows);
        } else {
//            if (!this.isProjectHeader(projectPlan.getId())) {
//                return ResponseInfo.error("项目负责人才可编辑");
//            }
            //已完成计划不可编辑
            ProjectPlan temp = this.getById(projectPlan.getId());
            if (temp.getState().equals(ProjectPlan.STATE_COMPLETE)) {
                return ResponseInfo.error("已完成计划项目不可编辑");
            }
            //编辑
            return edit(projectPlan);
        }
    }

    /**
     * 判断当前用户是否项目负责人
     *
     * @param projectPlanId
     * @return
     */
    @Override
    public Boolean isProjectHeader(String projectPlanId) {
        //管理员和老板有权限
        boolean f= roleService.hasRoles(new String[]{"admin"},SysUtil.getLoginUserId(request));
        if (f){
            return f;
        }
        QueryWrapper<ProjectMember> qw = new QueryWrapper<>();
        qw.eq("project_id", projectPlanId);
        qw.eq("identity_type", ProjectMember.IDENTITY_IDENTITY_TYPE_HEADER);//查询项目负责人
        List<ProjectMember> list = projectMemberService.list(qw);
        if (list.size() == 0) {
            return false;
        }
        for (ProjectMember projectMember : list) {
            if (projectMember.getUserId().equals(SysUtil.getLoginUserId(request))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 新增计划
     *
     * @param projectPlan
     * @return
     */
    private Map<String, Object> add(ProjectPlan projectPlan, List<ProjectMember> projectMembers, List<ProjectWorkFlow> projectWorkFlows) {
        if(StringUtil.iszNull(projectPlan.getId())){
            return ResponseInfo.error("主键要通过前台上传");
        }
        projectPlan.setState(PersonalPlan.STATE_UNCOMPLETED);//未完成状态
        projectPlan.setUserId(SysUtil.getLoginUserId(request));
        projectPlan.setCreateTime(LocalDateTime.now());
        //保存
        this.save(projectPlan);
        //添加创建人到项目团队
        this.addMembers(projectPlan, projectMembers);
        //添加工序到项目团队
//        workFlowService.addWorkFlow(projectPlan.getId(), projectWorkFlows,null);
        return ResponseInfo.success();
    }
    /**
     * 编辑项目成员
     * @param projectPlan
     * @param projectMembers
     */
    private void  editMembers(ProjectPlan projectPlan, List<ProjectMember> projectMembers) {
        //总奖金
        double totalBonus = projectPlan.getInitialBonus() + projectPlan.getAdditionalBonus();
        double totalPersonBonus = 0d;
        String projectPlanId = projectPlan.getId();
        //从数据库中找以前的成员
        QueryWrapper<ProjectMember> qw = new QueryWrapper<>();
        qw.eq("project_id", projectPlanId);
        //获取当前已有成员id
        List<ProjectMember> list = projectMemberService.list(qw);
        List<String> memberIds = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ProjectMember member = list.get(i);
            memberIds.add(member.getUserId());
        }
        //删除不一样的
        List<String> listNowIds=new ArrayList<>();
        for (int i = 0; i < projectMembers.size(); i++) {
            ProjectMember member = projectMembers.get(i);
            listNowIds.add(member.getId());
        }
        //检查数据类型
        for (ProjectMember pmold :
                list) {
            String userId = pmold.getUserId();
            for (int index = 0; index < projectMembers.size(); index++) {
                if (projectMembers.get(index).getUserId().equals(userId) && !pmold.getId().equals(projectMembers.get(index).getId())) {
                    throw new RuntimeException("参数结构错误保存失败！");
                }
            }
        }

        for (ProjectMember pmold :
                list) {
            if(listNowIds.contains(pmold.getId())==false){
                projectMemberService.removeById(pmold.getId());
            }
        }
//        projectMemberService.remove(qw);
        //要发送的通知列表
        List<TopicMessage> topicMessageList = new ArrayList<>();
        //添加创建人到项目团队
        int headCount = 0;
        for (int i = 0; i < projectMembers.size(); i++) {
            ProjectMember member = projectMembers.get(i);
            totalPersonBonus = member.getPersonalBonus() + totalPersonBonus;//累加奖金
            if (StringUtils.isEmpty(member.getUserId())) {
                throw new RuntimeException("错误的成员userId");
            }
            if (SysUtil.PROJECT_MEMBER_IDENTITY_TYPE_MAP.get(member.getIdentityType()) == null) {
                throw new RuntimeException("错误的成员类型");
            }
//            if (ProjectMember.IDENTITY_IDENTITY_TYPE_HEADER == member.getIdentityType()) {
//                headCount = headCount + 1;
//            }
//            member.setId(SysUtil.UUID());
            if (StringUtils.isEmpty(member.getId())) {
                throw new RuntimeException("错误的成员uuid");
            }
            member.setProjectId(projectPlanId);
            //用户id不在已有成员id列表中，属于新成员，发送信息
            if (memberIds.contains(member.getUserId()) == false) {
            member.setCreateTime(LocalDateTime.now());
            TopicMessage message = new TopicMessage();
            message.setId(SysUtil.UUID());
            message.setContent(member.getName()+", 您已成为 " + projectPlan.getName() + " 项目成员请确认");
            message.setTopicId(projectPlanId + "-type-" + TopicMessage.TYPE_PROJECT_GROUP);
            message.setBakTopicId(projectPlanId + "-type-" + TopicMessage.TYPE_PROJECT_GROUP);
            message.setReplyUserId(member.getUserId());
            message.setType(TopicMessage.TYPE_PROJECT_GROUP);
            message.setCreateTime(LocalDateTime.now());
            message.setUserId(projectPlan.getUserId());
            message.setIsRead(TopicMessage.UNREAD);
            message.setBeRead(TopicMessage.UNREAD);
            topicMessageList.add(message);
            }
        }
//        if (headCount != 1) {
//            throw new RuntimeException("项目成员必须且只能有一个项目负责人");
//        }
        if (totalPersonBonus > totalBonus) {
            throw new RuntimeException("个人奖金总额不可超过总奖金");
        }
        projectMemberService.saveOrUpdateBatch(projectMembers);
        topicMessageService.saveBatch(topicMessageList);
    }
    /**
     * 添加项目成员
     *
     * @param projectPlan
     * @param projectMembers
     */
    private void addMembers(ProjectPlan projectPlan, List<ProjectMember> projectMembers) {
        //总奖金
        double totalBonus = projectPlan.getInitialBonus() + projectPlan.getAdditionalBonus();
        double totalPersonBonus = 0d;
        String projectPlanId = projectPlan.getId();
        //先删除全部
//        QueryWrapper<ProjectMember> qw = new QueryWrapper<>();
//        qw.eq("project_id", projectPlanId);
        //获取当前已有成员id
//        List<ProjectMember> list = projectMemberService.list(qw);
//        List<String> memberIds = new ArrayList<>();
//        for (int i = 0; i < list.size(); i++) {
//            ProjectMember member = list.get(i);
//            memberIds.add(member.getUserId());
//        }
//        projectMemberService.remove(qw);
        //要发送的通知列表
        List<TopicMessage> topicMessageList = new ArrayList<>();
        //添加创建人到项目团队
        int headCount = 0;
        for (int i = 0; i < projectMembers.size(); i++) {
            ProjectMember member = projectMembers.get(i);
            member.setCreateTime(LocalDateTime.now());
            totalPersonBonus = member.getPersonalBonus() + totalPersonBonus;//累加奖金
            if (StringUtils.isEmpty(member.getUserId())) {
                throw new RuntimeException("错误的成员userId");
            }
            if (SysUtil.PROJECT_MEMBER_IDENTITY_TYPE_MAP.get(member.getIdentityType()) == null) {
                throw new RuntimeException("错误的成员类型");
            }
//            if (ProjectMember.IDENTITY_IDENTITY_TYPE_HEADER == member.getIdentityType()) {
//                headCount = headCount + 1;
//            }
//            member.setId(SysUtil.UUID());
            if (StringUtils.isEmpty(member.getId())) {
                throw new RuntimeException("错误的成员uuid");
            }
            member.setProjectId(projectPlanId);
            //用户id不在已有成员id列表中，属于新成员，发送信息
//            if (memberIds.contains(member.getUserId()) == false) {
                TopicMessage message = new TopicMessage();
                message.setId(SysUtil.UUID());
                message.setContent("您已成为 " + projectPlan.getName() + " 项目成员");
                message.setContent(member.getName()+",您已成为 " + projectPlan.getName() + " 项目成员请确认!");
                message.setBakTopicId(projectPlanId + "-type-" + TopicMessage.TYPE_PROJECT_GROUP);
                message.setReplyUserId(member.getUserId());
                message.setType(TopicMessage.TYPE_PROJECT_GROUP);
                message.setCreateTime(LocalDateTime.now());
                message.setUserId(projectPlan.getUserId());
                message.setIsRead(TopicMessage.UNREAD);
                message.setBeRead(TopicMessage.UNREAD);
                topicMessageList.add(message);
//            }
        }
//        if (headCount != 1) {
//            throw new RuntimeException("项目成员必须且只能有一个项目负责人");
//        }
        if (totalPersonBonus > totalBonus) {
            throw new RuntimeException("个人奖金总额不可超过总奖金");
        }
        projectMemberService.saveBatch(projectMembers);
        topicMessageService.saveBatch(topicMessageList);
    }



    /**
     * 更新计划
     *
     * @param projectPlan
     * @return
     */
    private Map<String, Object> edit(ProjectPlan projectPlan) {
        UpdateWrapper<ProjectPlan> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("remark", projectPlan.getRemark());
        updateWrapper.set("start_time", projectPlan.getStartTime());
        updateWrapper.set("end_time", projectPlan.getEndTime());
        updateWrapper.set("content", projectPlan.getContent());//设置工作内容
        updateWrapper.set("name", projectPlan.getName());//设置工作内容
        updateWrapper.set("progress", projectPlan.getProgress());//设置进度
        updateWrapper.set("progress_day", projectPlan.getProgressDay());//设置进度(天)
        updateWrapper.set("initial_bonus", projectPlan.getInitialBonus());//初始奖金
        updateWrapper.set("additional_bonus", projectPlan.getAdditionalBonus());//初始额外
        updateWrapper.set("rate", projectPlan.getRate());//项目星级
        updateWrapper.set("depart_id", projectPlan.getDepartId());//项目星级
        updateWrapper.eq("id", projectPlan.getId());
        updateWrapper.set("progress_money", projectPlan.getProgressMoney());
        updateWrapper.set("total_money", projectPlan.getTotalMoney());
        updateWrapper.set("gl_gx", projectPlan.getGlGx());
        updateWrapper.set("gl_zj", projectPlan.getGlZj());
        updateWrapper.set("gl_ts", projectPlan.getGlTs());
        updateWrapper.set("agree_time", projectPlan.getAgreeTime());
        this.update(updateWrapper);
        //添加创建人到项目团队
//        this.addMembers(projectPlan, projectPlan.getProjectMemberList());
        this.editMembers(projectPlan, projectPlan.getProjectMemberList());
        //添加工序到项目团队
//        workFlowService.addWorkFlow(projectPlan.getId(), projectPlan.getProjectWorkFlowList(),null);
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> dele(String id) {
        //只有经理，总经理，老板有权限新增编辑删除
//        String[] roles=new String[]{SysUtil.ROLE_FLAG_JL,SysUtil.ROLE_FLAG_ZJL,SysUtil.ROLE_FLAG_BOSS};
//        boolean flag=roleService.hasRoles(roles,SysUtil.getLoginUserId(request));
//        if (flag==false){
//            return ResponseInfo.error("当前账号无权限，必须是【经理，总经理，老板】角色账户");
//        }
        //已完成计划不可删除
        ProjectPlan temp = this.getById(id);
        if ((!SysUtil.getLoginUserId(request).equals("21"))&&!this.isProjectHeader(temp.getId())) {
            return ResponseInfo.error("项目负责人才可删除");
        }
        if (temp.getState().equals(PersonalPlan.STATE_COMPLETE)) {
            return ResponseInfo.error("已完成项目计划不可删除");
        }
        //删除项目成员 关联暂时不可删除
        //删除成员关联个人计划 关联暂时不可删除
        this.baseMapper.deleteById(id);//删除项目计划
        topicMessageService.deleteByTopicId(id);//删除关联留言
        attachmentListService.deleteByTargetId(id);//删除关联附件
        workFlowService.deleByPlanId(id);//删除关联工序
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> stateChange(String id, Integer state) {
        ProjectPlan projectPlan = this.getById(id);
        if (!this.isProjectHeader(projectPlan.getId())) {
            return ResponseInfo.error("项目负责人才可更改");
        }

        if (projectPlan == null) {
            return ResponseInfo.error("计划已经不存在的错误");
        }
        if (state != ProjectPlan.STATE_COMPLETE && state != ProjectPlan.STATE_UNCOMPLETED) {
            return ResponseInfo.error("错误的参数");
        }
        if (projectPlan.getState() == state) {
            return ResponseInfo.error("状态已改变");
        }
        projectPlan.setState(state);
        String completeTime = null;
        UpdateWrapper uw = new UpdateWrapper();
        uw.eq("id", id);
        uw.set("state", state);
        if (state == ProjectPlan.STATE_COMPLETE) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime localDateTimeNow = LocalDateTime.now();
            String localDateTimeNowStr = localDateTimeNow.format(formatter);
            completeTime = localDateTimeNowStr;
            uw.set("complete_time", LocalDateTime.now());
        } else {
            uw.set("complete_time", null);
        }
        this.update(uw);
        return ResponseInfo.success(completeTime);
    }

    /**
     * 根据项目计划project查询相关细分任务
     *
     * @param inputParam
     * @return
     */
    @Override
    public Map<String, Object> taskList(InputParam inputParam) {
        if (StringUtils.isEmpty(inputParam.getProject())) {
            return ResponseInfo.error("错误的参数");
        }
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = this.baseMapper.getPlanCalendar(inputParam);
        Long total = this.baseMapper.getPlanCalendarTotal(inputParam);
        //查询每个任务的个人任务
        for (Map<String, Object> record : list) {
            QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
            qw.eq("project_id", inputParam.getProject());
            qw.eq("work_date", record.get("work_date"));
            List<PersonalPlan> personalPlans = personalPlanService.list(qw);
            for (int i = 0; i < personalPlans.size(); i++) {
                PersonalPlan temp = personalPlans.get(i);
                BaseUser user = userService.getById(temp.getUserId());
                temp.setUser(user);
            }
            record.put("taskList", personalPlans);
        }
        map.put("rows", list);
        map.put("total", total);
        map.put("code", 1);
        return map;
    }

    /**
     * 查询所有项目成员指定日期项目计划
     *
     * @param projectPlanId
     * @param workDate
     * @return
     */
    @Override
    public Map<String, Object> memberTaskList(String projectPlanId, String workDate) {
        Map<String, Object> map = new HashMap<>();
        //查询所有项目成员
        QueryWrapper<ProjectMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectPlanId);
        List<ProjectMember> list = projectMemberService.list(queryWrapper);
        //查询每个成员当天的项目任务
        for (int i = 0; i < list.size(); i++) {
            ProjectMember member = list.get(i);
            //查询每个成员当天的项目任务
            QueryWrapper<PersonalPlan> qw = new QueryWrapper<>();
            qw.eq("work_date", workDate);
            qw.eq("user_id", member.getUserId());
            qw.eq("project_id", projectPlanId);
            qw.orderByAsc("start_time", "end_time");
            List<PersonalPlan> personalPlans = personalPlanService.list(qw);
            member.setPersonalPlanList(personalPlans);
            //查询每个成员名称
            BaseUser user = userService.getById(member.getUserId());
            member.setUser(user);
        }
        map.put("rows", list);
        map.put("code", 1);
        return map;
    }

    /**
     * 按照最近完成工序排序的项目记录
     *
     * @param inputParam
     * @return
     */
    @Override
    public Map<String, Object> getRecentCompletePlan(InputParam inputParam) {
        QueryWrapper ew = new QueryWrapper<ProjectPlan>();
        ew.eq("state", ProjectPlan.STATE_UNCOMPLETED);
        ew.orderByDesc("create_time");
        Page<ProjectPlan> result = this.page(new Page<ProjectPlan>(
                inputParam.getPage(),
                inputParam.getSize()), ew);
        List<Map<String, Object>> data = new ArrayList<>();
        List<ProjectPlan> list = result.getRecords();
        for (int i = 0; i < list.size(); i++) {
            ProjectPlan plan = list.get(i);
            Map<String, Object> map = new HashMap<>();
            map.put("projectPlan", plan);
            //查询项目负责人
            QueryWrapper<ProjectMember> projectMemberQueryWrapper = new QueryWrapper<>();
            projectMemberQueryWrapper.eq("project_id", plan.getId());
            projectMemberQueryWrapper.eq("identity_type", ProjectMember.IDENTITY_IDENTITY_TYPE_HEADER);
            List<ProjectMember> projectMemberList = projectMemberService.list(projectMemberQueryWrapper);
            List<BaseUser> headers = new ArrayList<>();
            for (int j = 0; j < projectMemberList.size(); j++) {
                //查询用户信息
                ProjectMember projectMember = projectMemberList.get(j);
                BaseUser user = userService.getById(projectMember.getUserId());
                projectMember.setUser(user);
                //查询用户部门信息
                List<BaseDepartment> departList = departmentService.findByUserId(user.getId());
                if (departList.size() > 0) {
                    user.setDepartment(departList.get(0));
                }
                headers.add(user);
            }
            map.put("headers", headers);
            data.add(map);
        }
        Map<String,Object> res=new HashMap<>();
        res.put("code",1);
        res.put("data",data);
        res.put("total",result.getTotal());
        return res;

//        List<ProjectWorkFlow> projectWorkFlows=projectWorkFlowDao.getRecentCompleteGroupByProjectPlan(inputParam);
//        List<Map<String,Object>> list=new ArrayList<>();
//        for (int i = 0; i <projectWorkFlows.size() ; i++) {
//            Map<String,Object> temp=new HashMap<>();
//            ProjectWorkFlow workFlow=projectWorkFlows.get(i);
//            ProjectPlan projectPlan=this.getById(workFlow.getProjectPlanId());
//            temp.put("projectPlan",projectPlan);//项目计划相关
//            //查询项目负责人
//            QueryWrapper<ProjectMember> projectMemberQueryWrapper=new QueryWrapper<>();
//            projectMemberQueryWrapper.eq("project_id",projectPlan.getId());
//            projectMemberQueryWrapper.eq("identity_type",ProjectMember.IDENTITY_IDENTITY_TYPE_HEADER);
//            List<ProjectMember> projectMemberList=projectMemberService.list(projectMemberQueryWrapper);
//            List<BaseUser> headers=new ArrayList<>();
//            for (int j = 0; j <projectMemberList.size() ; j++) {
//                //查询用户信息
//                ProjectMember projectMember=projectMemberList.get(j);
//                BaseUser user=userService.getById(projectMember.getUserId());
//                projectMember.setUser(user);
//                //查询用户部门信息
//                List<BaseDepartment> departList = departmentService.findByUserId(user.getId());
//                if (departList.size()>0){
//                    user.setDepartment(departList.get(0));
//                }
//                headers.add(user);
//            }
//            temp.put("headers",headers);
//            //查询进度信息
//            //1、查询所有工作流
//            QueryWrapper<ProjectWorkFlow> projectWorkFlowQueryWrapper=new QueryWrapper<>();
//            projectWorkFlowQueryWrapper.eq("project_plan_id",projectPlan.getId());
//            projectWorkFlowQueryWrapper.orderByAsc("step");
//            List<ProjectWorkFlow> workFlows=projectWorkFlowDao.selectList(projectWorkFlowQueryWrapper);
//            temp.put("total",workFlows.size());//总工序数
//            temp.put("nowStep",0);//最新完成东西序号
//            for (int j =workFlows.size()-1; j >=0 ; j--) {
//                if (workFlows.get(j).getStatus()==ProjectWorkFlow.STATUS_COMPLETE){
//                    temp.put("nowStep",j+1);//最新完成东西序号
//                    break;
//                }
//            }
//            list.add(temp);//查询计划
//        }
//        Map<String,Object> map=new HashMap<>();
//        map.put("rows", list);
//        map.put("code", 1);
//        return map;
    }

    /**
     * 获取当前个人项目进度
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getPersonProgress(String id) {
        QueryWrapper<ProjectMember> qw = new QueryWrapper<>();
        qw.eq("project_id", id);
        qw.eq("user_id", SysUtil.getLoginUserId(request));
        List<ProjectMember> list = projectMemberService.list(qw);
        if (list.size() == 0) {
            return ResponseInfo.error("当前账号并非项目成员");
        }
        return ResponseInfo.success(list.get(0));
    }

    /**
     * 编辑当前个人项目进度
     *
     * @param id
     * @param progress
     * @return
     */
    @Override
    public Map<String, Object> editPersonProgress(String id, Integer progress) {
        //已完成计划不可编辑
//        ProjectPlan temp=this.getById(id);
//        if (temp.getState()==ProjectPlan.STATE_COMPLETE){
//            return ResponseInfo.error("已完成计划项目不可编辑");
//        }
        String userId = SysUtil.getLoginUserId(request);
        UpdateWrapper<ProjectMember> qw = new UpdateWrapper<>();
        qw.eq("project_id", id);
        qw.eq("user_id", userId);
        qw.set("progress", progress);
        projectMemberService.update(qw);
        return ResponseInfo.success();
    }

    /**
     * 项目统计
     *
     * @param inputParam id  部门id
     * @param inputParam name 用户名
     * @param inputParam month 月分
     * @return
     */
    @Override
    public Map<String, Object> statisticalByUser(InputParam inputParam) {
        if (StringUtils.isEmpty(inputParam.getMonth())) {
            return ResponseInfo.error("参数错误-月份");
        }
        //月份数据
        LocalDate month = LocalDate.parse(inputParam.getMonth() + "-01",
                DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //获取这个月第一天
//        LocalDate month_firstDay=LocalDate.of(month.getYear(),month.getMonth(),1);
//        System.out.println("获取这个月第一天  "+month);
        //获取这个月最后一天
        LocalDate month_lastDay = month.with(TemporalAdjusters.lastDayOfMonth());
//        System.out.println("获取这个月最后一天  "+month_lastDay);
        //特殊处理，若部门id存在，则改成in查询
        if (org.apache.commons.lang.StringUtils.isNotEmpty(inputParam.getId())) {
            String temp = " (";
            String[] idArr = inputParam.getId().split(",");
            List<String> idList = new ArrayList<>();
            for (int i = 0; i < idArr.length; i++) {
                idList.add("'" + idArr[i] + "'");
            }
            String idtemp = idList.stream().map(String::valueOf).collect(Collectors.joining(","));
            temp += idtemp + ") ";
            inputParam.setId(temp);
        }
        if (inputParam.getPage() == null || inputParam.getSize() == null) {
            return ResponseInfo.error("参数错误");
        }

        inputParam.setOffset((inputParam.getPage() - 1) * inputParam.getSize());
        //安装部门分页查询相关用户信息
        List<BaseUser> list = userDao.getUsersByDepart(inputParam);

        List<Map<String, Object>> dataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            BaseUser user = list.get(i);
            //设置用户信息
            Map<String, Object> data = new HashMap<>();
            data.put("user", user);
            //设置统计信息
            Map<String, Object> participationProjectData = new HashMap<>();
            //参与项目数
            QueryWrapper<ProjectMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", user.getId());
            List<ProjectMember> memberList = projectMemberService.list(queryWrapper);
            Set<String> projectIdSet = new HashSet<>();
            //保存项目id与成员关系
            Map<String,ProjectMember> projectMemberMap=new HashMap<>();
            for (int j = 0; j < memberList.size(); j++) {
                projectIdSet.add(memberList.get(j).getProjectId());
                projectMemberMap.put(memberList.get(j).getProjectId(),memberList.get(j));
            }
            participationProjectData.put("totalNum", projectIdSet.size());
            int currentMonthWorkNum = 0;//当前月执行项目数
            int currentMonthCompleteNum = 0;//前月完成项目数
            int unCompleteNum = 0;//未完成项目数
            double currentMonthBonus = 0;//当前月应发项目奖金
//            System.out.println(projectIdSet);
            //有参与项目才统计计算
            if (projectIdSet.size() > 0) {
                QueryWrapper<ProjectPlan> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.in("id", projectIdSet);
                List<ProjectPlan> projectPlanList = this.list(queryWrapper1);
                for (int j = 0; j < projectPlanList.size(); j++) {
                    ProjectPlan project = projectPlanList.get(j);
                    //记录未完成的，在本月中的项目个数
                    if (project.getState() == ProjectPlan.STATE_UNCOMPLETED) {
                        unCompleteNum=unCompleteNum+1;
                        LocalDate endTime = project.getEndTime();//结束日期
                        LocalDate startTime = project.getStartTime();//开始日期
//                        System.out.println("项目结束日期"+endTime);
//                        System.out.println("本月最大日期"+month_lastDay);
                        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM");
                        String temp=month.format(formatter);
                        String endTemp=endTime.format(formatter);
                        String statrtTemp=startTime.format(formatter);
//                        boolean flag=endTime.isAfter(month_lastDay)||endTime.isEqual(month_lastDay);//本月最大日期小于等于项目结束时间
//                        flag=flag&&(startTime.isBefore(month)||startTime.isEqual(month));//本月最小日期大于等于项目结束时间
                        boolean flag=temp.compareTo(endTemp)<=0&&temp.compareTo(statrtTemp)>=0;
                        if (flag){
                            currentMonthWorkNum=currentMonthWorkNum+1;
                        }
                    }
                    //记录本月完成的，在本月中的项目个数
                    if (project.getState() == ProjectPlan.STATE_COMPLETE) {
                        LocalDate complete = project.getCompleteTime().toLocalDate();//结束日期
                        boolean flag=month_lastDay.isAfter(complete)||month_lastDay.isEqual(complete);//项目结束时间小于等于本月最大日期
                        flag=flag&&(month.isBefore(complete)||month.isEqual(complete));//项目结束时间大于等于本月最小日期
                        if (flag){
                            currentMonthCompleteNum=currentMonthCompleteNum+1;
                            //累加奖金
                           ProjectMember temp= projectMemberMap.get(project.getId());
                            currentMonthBonus=currentMonthBonus+temp.getPersonalBonus();
                        }
                    }
                }
            }
            participationProjectData.put("unCompleteNum",unCompleteNum);
            participationProjectData.put("currentMonthWorkNum",currentMonthWorkNum);
            participationProjectData.put("currentMonthCompleteNum",currentMonthCompleteNum);
            participationProjectData.put("currentMonthBonus",currentMonthBonus);
            //同意数目
            QueryWrapper<ProjectMember> qw=new QueryWrapper<>();
            qw.eq("user_id",user.getId());
            qw.eq("agree_status",1);
            int agreeCount = projectMemberService.count(qw);
            participationProjectData.put("agreeCount",agreeCount);

            QueryWrapper<TopicUserRefuseCount> qw2=new QueryWrapper<>();
            qw2.eq("user_id",user.getId());
            int disagreeCount = topicUserRefuseCountService.count(qw2);
            participationProjectData.put("disagreeCount",disagreeCount);

            data.put("participationProjectData", participationProjectData);
            dataList.add(data);

        }
        Map<String, Object> map = new HashMap<>();
        map.put("rows", dataList);
        map.put("total", userDao.totalUsersByDepart(inputParam));
        map.put("code", 1);
        return map;
    }

    /**
     * 查询用户指定月份项目奖金
     * @param userId 用户id，没有就是当前用户
     * @param month 月份数据 2023-06
     * @return
     */
    @Override
    public Map<String, Object> getProjectBonusByMonth(String userId, String month,InputParam param) {
        LocalDateTime month_start=null;//本月开始时间
        LocalDateTime month_end=null;//本月结束时间
        if(param.getStartDate()!=null&&param.getEndDate()!=null){
            LocalDate t=param.getStartDate();
            month_start=LocalDateTime.of(t.getYear(),t.getMonthValue(),t.getDayOfMonth(),0,0,0);
            t=param.getEndDate();
            month_end=LocalDateTime.of(t.getYear(),t.getMonthValue(),t.getDayOfMonth(),23,59,59);
        }else{
            try{
                month_start= LocalDateTime.parse(month + "-01 00:00:00",
                        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                month_end=month_start.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
                //月份数据
                LocalDate temp = LocalDate.parse(month + "-01",
                        DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }catch (Exception e){
                return ResponseInfo.error("参数错误-月份");
            }
        }
        System.out.println(month_start);
        System.out.println(month_end);
        //默认当前用户
        if (StringUtils.isEmpty(userId)) {
            userId=SysUtil.getLoginUserId(request);
        }
        QueryWrapper<ProjectPlan> queryWrapper=new QueryWrapper();
        queryWrapper.inSql("id","select project_id from project_member where user_id ='"+userId+"'");
        queryWrapper.eq("state",ProjectPlan.STATE_COMPLETE);//查询已完成任务
        queryWrapper.between("complete_time",month_start,month_end);//完成时间在本月范围
        Page<ProjectPlan> result = this.page(new Page<ProjectPlan>(
                param.getPage(),
                param.getSize()), queryWrapper);
        List<ProjectPlan> list=this.list(queryWrapper);
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> data=new HashMap<>();
            //项目信息
            ProjectPlan projectPlan=list.get(i);
            data.put("project",projectPlan);
            //成员信息
            QueryWrapper<ProjectMember> qw=new QueryWrapper();
            qw.eq("project_id",projectPlan.getId());
            qw.eq("user_id",userId);
            ProjectMember projectMember=projectMemberService.getOne(qw);
            data.put("projectMember",projectMember);
            dataList.add(data);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("rows", dataList);
        map.put("total", result.getTotal());//总记录数
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> getMemberById(String projectId, String userId) {
        if(StringUtils.isEmpty(projectId) ||StringUtils.isEmpty(userId) ) {
            return ResponseInfo.error("错误的参数");
        }
        //查询成员
        QueryWrapper<ProjectMember> qw = new QueryWrapper<>();
        qw.eq("project_id", projectId);
        qw.eq("user_id", userId);
        List<ProjectMember> projectMemberList = projectMemberService.list(qw);
        if(projectMemberList.size()>0){
            return ResponseInfo.success(projectMemberList.get(0));
        }
        return ResponseInfo.success();
    }
}
